<template>
  <div class="pre">
    <el-dropdown v-if="editor">
      <span class="el-dropdown-link">
        添加后置操作
      </span>
      <template #dropdown>
        <el-dropdown-menu>
          <!-- <el-dropdown-item :icon="Edit" @click="handleMenu('CustomScript')">自定义脚本</el-dropdown-item>
          <el-dropdown-item :icon="DocumentAdd" @click="handleMenu('CommonScript')">公共脚本</el-dropdown-item>
          <el-dropdown-item :icon="Timer" @click="handleMenu('WaitTime')">等待时间</el-dropdown-item>
          <el-dropdown-item :icon="Download" @click="handleMenu('import')">从其他接口\用例\目录导入</el-dropdown-item> -->
          <el-dropdown-item :icon="Key" @click="handleExtractVar">提取变量</el-dropdown-item>
          <el-dropdown-item :icon="Finished" @click="handleAssertion">断言</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
    <el-tree :data="treeData" :allow-drop="allowDrop" :allow-drag="allowDrag" draggable default-expand-all node-key="id"
      @node-drop="handleDrop" :expand-on-click-node="false" :props="defaultProps" :indent="22"
      @node-click="handleNodeClick" class="pre-tree" ref="treeRef" :check-on-click-node="true" :key="treeKey">
      <template #default="{ data }">
        <span class="pre-tree__node">
          <span class="label">
            <el-icon v-if="editor">
              <Operation />
            </el-icon>
            <el-checkbox v-model="data.status" label="" size="small" @change="changeStatus" v-if="editor" />
            <span class="type">{{ data.type == 'EXTRACTOR' ? '提取变量' : '断言' }}</span>
          </span>
          <span :class="data.type == 'EXTRACTOR' ? 'ml-76px' : 'ml-100px'">{{ data.name }} <small class="expression"> {{
            extractVarConfig[data.processType] }} {{
                extractVarConfig[data.source] }}<span v-if="data.processExpression">({{
                data.processExpression
              }})</span></small></span>
          <span class="operation" v-if="editor">
            <el-popover class="operation-popover" v-if="popoverVisible" @before-leave="hidePopver">
              <template #reference>
                <el-icon>
                  <MoreFilled />
                </el-icon>
              </template>
              <div class="operation-list">
                <p @click.stop="edit(data)"> <el-icon>
                    <Edit />
                  </el-icon> 编辑 </p>
                <p @click.stop="remove(data)"><el-icon>
                    <Remove />
                  </el-icon> 删除 </p>
              </div>
            </el-popover>
          </span>
        </span>
      </template>
    </el-tree>
    <AssertionForm ref="assertionFormRef" @success="handleAssertionSuccess" />
    <ExtractVarForm ref="extractVarFormRef" @success="handleExtractVarSuccess" />
  </div>
</template>

<script setup lang="ts">
import * as DebugApi from '@/api/debug'
import { MoreFilled, Operation, Edit, Remove, Key, Finished } from '@element-plus/icons-vue'
import { useAppStore } from '@/store/modules/app'
import AssertionForm from '../debug/dialog/prepost/AssertionForm.vue';
import ExtractVarForm from '../debug/dialog/prepost/ExtractVarForm.vue';
import { propTypes } from '@/utils/propTypes'
const treeKey = ref(0)
const appStore = useAppStore()
const projectId = computed(() => appStore.getSelectProject)
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const treeData = ref([] as any)
const emit = defineEmits(['postValue'])
const defaultProps = {
  children: 'children',
  label: 'name'
}
const treeRef = ref()
const assertionFormRef = ref()
const loading = ref(false)
const popoverVisible = ref(true)
const extractVarFormRef = ref()
const extractVarConfig = ref({
  'ENVIRONMENT_VARIABLE': '环境变量',
  'GLOBAL_VARIABLE': '全局变量',
  'TEMP_VARIABLE': '临时变量',
  'RESPONSE_TEXT': 'Response Text',
  'RESPONSE_JSON': 'Response JSON',
  'RESPONSE_HEADER': 'Response Header',
  '': ''
})
const props = defineProps({
  id: propTypes.string.def(''),
  data: propTypes.object.def({}),
  editor: propTypes.bool.def()
})
watch(() => props.data, (newVal, oldVal) => {
  if (JSON.stringify(newVal) != JSON.stringify(oldVal)) {
    init()
  }
}, {
  deep: true
})
const init = () => {
  if (props.data.post) {
    treeData.value = props.data.post.map(item => {
      return {
        ...item,
        status: (item.status === 0 || item.status === true) ? true : false
      }
    })
  } else {
    treeData.value = []
  }
  emit('postValue', treeData.value)
}
onMounted(() => {
  init()
})
/** 获取列表 */
const freshData = (id) => {
  const index = treeData.value.findIndex(item => item.id == id)
  treeData.value.splice(index, 1)
  treeKey.value++
  emit('postValue', treeData.value)
}
/** 点击记录 */
const handleNodeClick = () => {

}
/** 添加提取变量 */
const handleExtractVar = () => {
  extractVarFormRef.value.open('create')
}
/** 添加断言 */
const handleAssertion = () => {
  assertionFormRef.value.open('create')
}
/**
 * 重命名
 * */
const edit = (data) => {
  if (data.type.indexOf('EXTRACTOR') != -1) {
    extractVarFormRef.value.open('update', data, props.data, props.id)
  } else {
    assertionFormRef.value.open('update', data, props.data, props.id)
  }
}
/**
 * 删除
 * */
const remove = async (data) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // loading.value = true
    // 发起删除
    // if (data.type.indexOf('EXTRACTOR') != -1) {
    //   await DebugApi.deleteExtractor({ id: data.stepId })
    // } else {
    //   await DebugApi.deleteAssert({ id: data.stepId })
    // }
    // message.success(t('common.delSuccess'))
    // 刷新列表
    freshData(data.id)
  } catch (error) {
    console.log(error)
  } finally {
    // loading.value = false
  }
}
/** 断言添加成功后处理 */
const handleAssertionSuccess = (data, type) => {
  if (type == 'create') {
    treeData.value.push({
      id: data.id,
      name: data.name,
      stepId: data.id,
      processType: data.assertType,
      processExpression: data.expression,
      type: 'ASSERTION',
      status: true,
      source: ''
    })
  } else {
    treeData.value.forEach(item => {
      if (item.stepId == data.id) {
        item.name = data.name
        item.processType = data.assertType
        item.processExpression = data.expression
      }
    })
    treeKey.value++
  }
  emit('postValue', treeData.value)
}
/** 提取变量添加成功后处理 */
const handleExtractVarSuccess = (data, type) => {
  if (type == 'create') {
    treeData.value.push({
      id: data.id,
      name: data.name,
      stepId: data.id,
      processType: data.variableType,
      processExpression: data.expression,
      type: 'EXTRACTOR',
      status: true,
      source: data.source
    })
  } else {
    treeData.value.forEach(item => {
      if (item.stepId == data.id) {
        item.name = data.name
        item.processType = data.variableType
        item.processExpression = data.expression
        item.source = data.source
      }
    })
    treeKey.value++
  }
  emit('postValue', treeData.value)
}
/** 状态改变 */
const changeStatus = () => {
  emit('postValue', treeData.value)
}
/** 拖动树后保存 */
const handleDrop = async (draggingNode: Node, dropNode: Node, position) => {

}
/** 只有目录可以被拖入 */
const allowDrop = () => {
  return true
}
/** 只有接口、目录可以被拖动 */
const allowDrag = () => {
  return true
}
/**
 * 避免popover闪现bug
 * */
const hidePopver = () => {
  popoverVisible.value = false
  setTimeout(() => {
    popoverVisible.value = true
  }, 10)
}
</script>

<style scoped lang="scss">
.pre {
  padding-right: 10px;
  height: 100%;

  >.el-dropdown {
    width: 115px;
    height: 32px;
    line-height: 32px;
    display: flex;
    justify-content: center;
    color: var(--el-color-primary);
    border: 1px solid var(--el-color-primary-light-5);
    margin-bottom: 10px;
    border-radius: 4px;
    background-color: var(--el-color-primary-light-9);
    ;

    .el-icon {
      display: none;
    }

    &:hover {
      background-color: var(--el-color-primary);
      color: var(--el-color-white);
      border-color: var(--el-color-primary);
      cursor: pointer;
    }
  }
}

.pre-tree {
  overflow: auto !important;
  height: calc(100% - 45px) !important;
  margin-top: 10px;

  :deep(.el-tree-node) {
    height: auto !important;
  }

  :deep(.el-tree-node__content) {
    border: 1px solid var(--el-border-color-light);
    border-radius: 5px;
    padding: 5px;
    margin-bottom: 5px;

    .pre-tree__node {
      display: flex;
      // justify-content: space-between;
      width: calc(100% - 20px);
      padding: 0 10px;
      position: relative;
    }

    .type {
      border-style: solid;
      border-width: 1px;
      border-radius: 0 10px 10px 0;
      padding: 0 5px;
      margin-right: 5px;
      font-size: 12px;
      border-color: #409eff;
      color: #409eff;
    }

    .operation {
      position: absolute;
      right: 5px;
      top: 4px;
    }

    .operation-list {
      p {
        display: flex;
        align-items: center;
        border-bottom: 1px solid #ccc;
        padding-bottom: 10px;
        margin: 0 0 10px 0;
        cursor: pointer;

        .el-icon {
          margin-right: 10px;
        }

        &:last-child {
          border: none;
          margin-bottom: 0;
          padding: 0;
        }
      }
    }

    .label {
      display: flex;
      align-items: center;

      .el-icon {
        margin-right: 10px;
        cursor: move;
      }
    }

    >.el-icon {
      display: none;
    }
  }

  .expression {
    color: var(--el-text-color-secondary);
    font-size: 14px;
  }
}
</style>
